﻿using System;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using Designit.Umb.Newsletter.Bll;
using umbraco.BasePages;

namespace Designit.Umb.Newsletter.Custom.plugins.designit.newsletter
{
    public partial class TestMail : UmbracoEnsuredPage
    {
        private MailSettings _mailSettings;
        protected void Page_Load(object sender, EventArgs e)
        {
            _mailSettings = MailSettings.Get();
            if (!IsPostBack)
                txtModtager.Text = _mailSettings.TestMail;
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            var id = Int32.Parse(Request["id"]);

            using (var reader =
                umbraco.BusinessLogic.Application.SqlHelper.ExecuteReader("select * from newsLetterCampaignNewsletter where id=@id",
                    umbraco.BusinessLogic.Application.SqlHelper.CreateParameter("@id", id)))
            {
                while (reader.Read())
                {
                    var cont = EmbedNewsletter.EmbSend(reader.GetString("campTemplatecontent"),
                                                       reader.GetString("campcontent"), reader.GetString("campfrom"),
                                                       reader.GetString("campreplyMail"));

                    //replace href local tags 
                    const string regex = @"href=""(.*?)""";
                    foreach (var match in Regex.Matches(cont, regex, RegexOptions.IgnoreCase))
                    {
                        var url = match.ToString().Substring(6, match.ToString().Length - 7);
                        if (url.StartsWith("/{localLink"))
                        {
                            url = umbraco.library.NiceUrl(Int32.Parse(url.Substring(12, url.Length - 13)));
                            var regexLocal = @"href=""http://" + Request.ServerVariables.Get("HTTP_HOST") + url +
                                                @"""";
                            cont = Regex.Replace(cont, match.ToString(), regexLocal, RegexOptions.IgnoreCase);
                        }
                    }

                    var cl = new SmtpClient(_mailSettings.SmtpServer, _mailSettings.SmtpPort);

                    if (_mailSettings.SmtpAuth)
                        cl.Credentials = new NetworkCredential(_mailSettings.MailServerUsername, _mailSettings.MailServerPassword);

                    cont = Helper.InsertHostIntoLink(cont);

                    string[] lines = Regex.Split(txtModtager.Text, ",|;");
                    foreach (var s in lines)
                    {
                        var testMail = new MailMessage(_mailSettings.SenderMail, s);
                        var server = Helper.GetCurrentHostUrl();
                        if (!string.IsNullOrEmpty(testMail.Headers.Get("Content-Base")))
                            testMail.Headers["Content-Base"] = server;
                        else
                            testMail.Headers.Add("Content-Base", server);

                        if (!string.IsNullOrEmpty(testMail.Headers.Get("Content-Location")))
                            testMail.Headers["Content-Location"] = server;
                        else
                            testMail.Headers.Add("Content-Location", server);

                        testMail.Subject = reader.GetString("campsubject");

                        // SEND IN HTML FORMAT (comment this line to send plain text).
                        testMail.IsBodyHtml = true;

                        // HTML Body (remove HTML tags for plain text).
                        testMail.Body = cont;
                        cl.Send(testMail);
                    }


                }
            }
            ClientTools.ShowSpeechBubble(speechBubbleIcon.success, "Test mail sent", "");
            var sb = new StringBuilder();
            sb.AppendLine(@"<script type=""text/javascript"">");
            sb.AppendLine(ClientTools.Scripts.CloseModalWindow());
            sb.AppendLine("</script>");
            Page.ClientScript.RegisterStartupScript(GetType(), "close", sb.ToString());
        }
    }
}
